<template>
  <design-dialog
    :visible.sync="visible"
    wrapClassName="goods-sku-manager"
    width="1200px"
    :title="config.popop_title || '选择添加商品'"
    @isOk="handle_confirm"
    @isCancel="handle_cancel"
  >
    <div style="height: 50vh; overflow: auto">
      <div
        v-if="
          config.choose === 'good' &&
          (goods_type === 'list' || goods_type === 'store_good')
        "
      >
        <a-select
          style="width: 180px"
          v-model="goods_status"
          @change="currentChange(1)"
        >
          <a-select-option value=""> 商品状态 </a-select-option>
          <a-select-option value="1"> 上架 </a-select-option>
          <a-select-option value="0"> 下架 </a-select-option>
        </a-select>

        <a-select
          style="width: 180px"
          v-model="search_goods_type"
          @change="currentChange(1)"
        >
          <a-select-option value=""> 商品类型 </a-select-option>
          <a-select-option value="is_new"> 新品 </a-select-option>
          <a-select-option value="is_hot"> 热卖 </a-select-option>
          <a-select-option value="is_recommand"> 推荐 </a-select-option>
          <a-select-option value="is_discount"> 促销 </a-select-option>
        </a-select>

        <template v-if="is_from !== 'store'">
          <!--:getPopupContainer="triggerNode => {return triggerNode || document.body;}"-->
          <a-select
            v-model="parenttext"
            show-search
            placeholder="请选择一级分类"
            option-filter-prop="children"
            style="width: 180px"
            :filter-option="filterOption"
            @select="handleSelect"
            @popupScroll="popupScroll"
            @search="handleSearch"
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in categoryOne"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
            v-model="childtext"
            placeholder="请选择二级分类"
            option-filter-prop="children"
            style="width: 180px"
            :filter-option="filterOption"
            @select="handleSelect2"
            @popupScroll="popupScroll2"
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in categoryTwo"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
            v-model="thirdtext"
            placeholder="请选择三级分类"
            option-filter-prop="children"
            style="width: 180px"
            :filter-option="filterOption"
            @select="handleSelect3"
            @popupScroll="popupScroll3"
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in categoryThree"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
            v-model="selectedGood"
            style="width: 180px"
            @change="currentChange(1)"
          >
            <a-select-option value="1">排查已选商品</a-select-option>
            <a-select-option value="0">显示已选商品</a-select-option>
          </a-select>
          <div style="height: 10px"></div>
        </template>

        <a-input
          style="width: 45%; margin-bottom: 10px; margin-right: 10px"
          v-model.trim="keywords"
          placeholder="请输入关键字搜索"
        >
        </a-input>
        <a-button
          style="width: 90px"
          type="primary"
          @click.stop="currentChange(1)"
          >搜索</a-button
        >
      </div>
      <div v-else-if="config.choose === 'group' || config.choose === 'rush'">
        <a-select
          style="width: 200px"
          v-model="time_status1"
          @change="currentChange(1)"
          v-if="config.choose === 'group'"
        >
          <a-select-option value=""> 活动状态 </a-select-option>
          <a-select-option value="1"> 未开始 </a-select-option>
          <a-select-option value="2"> 进行中 </a-select-option>
        </a-select>

        <a-select
          style="width: 200px"
          v-model="time_status2"
          @change="currentChange(1)"
          v-if="config.choose === 'rush'"
        >
          <a-select-option value=""> 活动状态 </a-select-option>
          <a-select-option value="1"> 未开始 </a-select-option>
          <a-select-option value="2"> 活动中 </a-select-option>
        </a-select>

        <a-input
          style="width: 65%; margin-bottom: 10px; margin-right: 10px"
          v-model.trim="keywords"
          placeholder="请输入关键字搜索"
        >
        </a-input>
        <a-button
          style="width: 90px"
          type="primary"
          @click.stop="currentChange(1)"
          >搜索</a-button
        >
      </div>
      <div
        v-else-if="
          (config.choose === 'good' && goods_type === 'tag') ||
          (config.choose === 'good' && (goods_type === 'category'||goods_type === 'categoryDraggable'))
        "
      ></div>
      <div v-else-if="config.choose === 'good' && goods_type === 'project'">
        <a-select
          v-model="current_project_cate"
          placeholder="项目分类"
          style="width: 200px"
          @select="handleSelectProject"
        >
          <a-select-option
            :value="item.id"
            v-for="(item, index) in project_cate"
            :key="index"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-input
          style="width: 65%; margin-bottom: 10px; margin-right: 10px"
          v-model.trim="keywords"
          placeholder="请输入关键字搜索"
        >
        </a-input>
        <a-button
          style="width: 90px"
          type="primary"
          @click.stop="currentChange(1)"
          >搜索</a-button
        >
      </div>
      <div v-else>
        <a-input
          style="width: 85%; margin-bottom: 10px; margin-right: 10px"
          v-model.trim="keywords"
          placeholder="请输入关键字搜索"
        >
        </a-input>
        <a-button
          style="width: 90px"
          type="primary"
          @click.stop="currentChange(1)"
          >搜索</a-button
        >
      </div>
      <div>
        <div
          v-if="goods_type === 'tag' || goods_type === 'category'||goods_type === 'categoryDraggable'"
          style="padding: 10px 200px"
        >
          <el-tree
            :data="main_page_list"
            show-checkbox
            node-key="id"
            icon-class="iconfont icon-advertise-next"
            ref="tree"
            highlight-current
            @check="handleCheck"
            :props="defaultProps"
          >
          </el-tree>
        </div>

        <div v-if="goods_type !== 'tag' && goods_type !== 'category'&& goods_type !== 'categoryDraggable'">
          <a-table
            class="goods_tab"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onSelect: onSelectChange,
              onSelectAll: onSelectAll,
            }"
            :columns="columns"
            rowKey="id"
            :data-source="main_page_list"
            :pagination="false"
          >
            <div
              slot="goods_name"
              slot-scope="text, record"
              style="
                display: flex;
                justify-content: space-around;
                align-items: center;
              "
            >
              <span>{{ record.title }}</span>
              <div
                style="margin-left: 5px"
                v-if="
                  category_to_option_open == 1 &&
                  selectedRowKeys.indexOf(record.id) > -1 &&
                  record.has_many_goods_category &&
                  record.has_many_goods_category.length > 1
                "
              >
                <a-select
                  placeholder="可选择分类"
                  :default-value="record.category_id"
                  :allowClear="true"
                  style="width: 200px"
                  @change="handleCateChange(arguments, record)"
                >
                  <a-select-option
                    :value="item.category_id"
                    v-for="item in record.has_many_goods_category"
                    :key="item.id"
                  >
                    {{ item.category_name }}
                  </a-select-option>
                </a-select>
              </div>
            </div>
            <div slot="goods_title" slot-scope="text, record">
              <span v-if="record.goods">{{ record.goods.title }}</span>
            </div>
            <div slot="goods_img" class="goods_img" slot-scope="text, record">
              <img :src="record.thumb" />
            </div>
            <div
              slot="goods_group_img"
              class="goods_img"
              slot-scope="text, record"
            >
              <img v-if="record.goods" :src="record.goods.thumb" />
            </div>
            <div slot="price" slot-scope="text, record">
              <span v-if="record.goods">{{ record.group_price }}</span>
            </div>
            <div slot="stock" slot-scope="text, record">
              <span v-if="record.goods">{{ record.goods.price }}</span>
            </div>

            <div slot="store_name" slot-scope="text, record">
              <div class="store_box">
                <div style="flex: 0 0 100px; margin-right: 10px">
                  <img :src="record.thumb" />
                </div>
                <span style="flex: 1; text-align: left; align-self: center">{{
                  record.store_name
                }}</span>
              </div>
            </div>

            <div slot="hotel_name" slot-scope="text, record">
              <div class="store_box">
                <div style="flex: 0 0 100px; margin-right: 10px">
                  <img :src="record.thumb" />
                </div>
                <span style="flex: 1; text-align: left; align-self: center">{{
                  record.hotel_name
                }}</span>
              </div>
            </div>
          </a-table>
        </div>
      </div>
    </div>

    <div style="">
      <!-- #95740 注释样式 -->
      <!-- position: absolute;bottom: 80px;left: 50%;transform: translateX(-50%); -->
      <a-pagination
        style="margin-top: 15px; text-align: center"
        showQuickJumper
        :pageSize="main_page_pagination.pageSize"
        :current="main_page_pagination.current"
        :total="main_page_pagination.total"
        @change="currentChange"
      />
    </div>
  </design-dialog>
</template>

<script>
// import goodsList from '@/interface/json-data/get_goods_list.json';

const good_columns = [
  { title: "商品ID", align: "center", dataIndex: "id" },
  {
    title: "商品图片",
    align: "center",
    dataIndex: "thumb",
    width: 150,
    scopedSlots: { customRender: "goods_img" },
  },
  {
    title: "商品名称",
    align: "center",
    dataIndex: "title",
    width: 400,
    scopedSlots: { customRender: "goods_name" },
  },
  { title: "商品状态", align: "center", dataIndex: "status_name" },
  { title: "商品原价", align: "center", dataIndex: "market_price" },
  { title: "商品现价", align: "center", dataIndex: "price" },
  { title: "库存", align: "center", dataIndex: "stock" },
];

const group_columns = [
  { title: "拼团ID", align: "center", dataIndex: "id", width: 50 },
  { title: "拼团标题", align: "center", dataIndex: "title", width: 300 },
  {
    title: "拼团商品名称",
    align: "center",
    dataIndex: "goods_title",
    width: 300,
    scopedSlots: { customRender: "goods_title" },
  },
  {
    title: "拼团商品图片",
    align: "center",
    dataIndex: "thumb",
    key: "thumb",
    width: 150,
    scopedSlots: { customRender: "goods_group_img" },
  },
  {
    title: "拼团价",
    align: "center",
    dataIndex: "price",
    scopedSlots: { customRender: "price" },
  },
  {
    title: "商品现价",
    align: "center",
    dataIndex: "stock",
    scopedSlots: { customRender: "stock" },
  },
];

const tree_columns = [
  { title: "分类ID", align: "center", dataIndex: "id", width: 300 },
  { title: "分类标题", align: "center", dataIndex: "name" },
];

const supplier_columns = [
  { title: "ID", align: "center", dataIndex: "id", width: 300 },
  { title: "供应商账号", align: "center", dataIndex: "username" },
  { title: "供应商手机", align: "center", dataIndex: "mobile" },
];

const store_columns = [
  { title: "ID", align: "center", dataIndex: "id", width: 300 },
  {
    title: "门店名称",
    dataIndex: "store_name",
    width: 300,
    scopedSlots: { customRender: "store_name" },
  },
  { title: "地址", align: "center", dataIndex: "full_address" },
];

const hotel_columns = [
  { title: "ID", align: "center", dataIndex: "id", width: 300 },
  {
    title: "酒店名称",
    dataIndex: "hotel_name",
    width: 300,
    scopedSlots: { customRender: "hotel_name" },
  },
  { title: "地址", align: "center", dataIndex: "full_address" },
];

const star_columns = [
  { title: "活动ID", align: "center", dataIndex: "activity_id", width: 50 },
  {
    title: "活动标题",
    align: "center",
    dataIndex: "activity_name",
    width: 300,
  },
  {
    title: "活动商品名称",
    align: "center",
    dataIndex: "goods_title",
    width: 300,
    scopedSlots: { customRender: "goods_title" },
  },
  {
    title: "活动商品图片",
    align: "center",
    dataIndex: "thumb",
    key: "thumb",
    width: 150,
    scopedSlots: { customRender: "goods_group_img" },
  },
  {
    title: "拼团价",
    align: "center",
    dataIndex: "price",
    scopedSlots: { customRender: "price" },
  },
  {
    title: "商品现价",
    align: "center",
    dataIndex: "stock",
    scopedSlots: { customRender: "stock" },
  },
];

const project_columns = [
  { title: "ID", align: "center", dataIndex: "id", width: 100 },
  { title: "项目名称", align: "center", dataIndex: "title", width: 400 },
  { title: "分类ID", align: "center", dataIndex: "category_id" },
  { title: "分类名称", align: "center", dataIndex: "category_name" },
];

const store_category_columns = [
  { title: "ID", align: "center", dataIndex: "id", width: 100 },
  {
    title: "分类图标",
    align: "center",
    dataIndex: "thumb",
    key: "thumb",
    scopedSlots: { customRender: "goods_img" },
    width: 400,
  },
  { title: "分类名称", align: "center", dataIndex: "name" },
  { title: "是否开启", align: "center", dataIndex: "is_open" },
];
export default {
  name: "goods-sku",
  props: ["goods_type", "config", "is_from", "extinfo"],
  data() {
    return {
      selectedKey: {},
      oldAllcheckedKeys: [],
      oldAllSelectedList: [],//已选择的所有分类列表（包含一级二级三级）

      prevChangePages: 1,//记录上一页的页数
      category_to_option_open: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      time_status1: " ",
      time_status2: " ",
      search_goods_type: " ",
      goods_status: " ",
      keywords: "",
      visible: false,
      treeSelects: [[]], // 树状数据列表
      // list: goodsList.data, // 商品列表
      selectedRowKeys: [], // 复选框选中
      selectedRows: [],
      group_columns,
      good_columns,
      url: "",
      // 主页列表
      old_main_page_list: [],
      main_page_list: [],
      // 主分页的页码
      main_page_pagination: {
        current: 1,
        pageSize: 20,
        total: 0,
      },
      current_project_cate: "",
      project_cate: [],

      // 单个选择分类
      parentid: "",
      childid: "",
      thirdid: "",
      search_title: "",
      parenttext: "",
      childtext: "请选择二级分类",
      thirdtext: "请选择三级分类",
      categoryOne: [],
      categoryOneCurrent: 1,
      categoryOneTotal: 2, //为了第一次加载需要先设置为2
      categoryTwo: [],
      categoryTwoCurrent2: 1,
      categoryTwoTotal2: 2,
      categoryThree: [],
      categoryThreeCurrent3: 1,
      categoryThreeTotal3: 2,

      selectedGood: "1", //是否排查已选商品，不显示已选商品
    };
  },
  computed: {
    columns() {
      switch (this.goods_type) {
        case "list":
        case "store_good":
          return good_columns;
        case "rush":
          return good_columns;
        case "group":
          return group_columns;
        case "category":
          return tree_columns;
        case "categoryDraggable":
          return tree_columns;
        case "tag":
          return tree_columns;
        case "supplier":
          return supplier_columns;
        case "store":
          return store_columns;
        case "hotel":
          return hotel_columns;
        case "starGroup":
          return star_columns;
        case "project":
          return project_columns;
        case "store_category":
          return store_category_columns;
        default:
          return good_columns;
      }
    },
  },
  mounted() {},
  methods: {
    handleCateChange(value, record) {
      record.category_id = value[0] || "";
      let obj = [];
      let old_obj = [];
      old_obj = this.old_main_page_list.filter((item) => {
        return item.id == record.id;
      });
      if (value[0]) {
        // 选中分类
        obj = record.has_many_goods_category.filter((item) => {
          return item.category_id == value[0];
        });
        if (obj[0] && obj[0].goods_option) {
          record.thumb = obj[0].goods_option.thumb || old_obj[0].thumb;
          record.price = obj[0].goods_option.product_price;
          record.market_price = obj[0].goods_option.market_price;
        } else {
          // 分类没有绑定规格
          if (old_obj[0]) {
            record.thumb = old_obj[0].thumb;
            record.price = old_obj[0].price;
            record.market_price = old_obj[0].market_price;
          }
        }
      } else {
        // 清空分类
        if (old_obj[0]) {
          record.thumb = old_obj[0].thumb;
          record.price = old_obj[0].price;
          record.market_price = old_obj[0].market_price;
        }
      }
      for (let i = 0; i < this.selectedRows.length; i++) {
        // 更新selectedRows
        if (this.selectedRows[i].id == record.id) {
          this.selectedRows[i] = record;
        }
      }
    },
    handleSearch(value) {
      this.search_title = value;
      this.categoryOneCurrent = 1;
      this.categoryOneTotal = 2;
      this.getCategoryOne(1);
    },
    handleSelect(value) {
      let choose = this.categoryOne.filter((item) => {
        return item.id == value;
      });
      if (choose.length > 0) {
        this.parentid = choose[0].id;
        // 选择后初始化分页
        this.categoryTwo = [];
        this.categoryThree = [];
        this.childtext = "请选择二级分类";
        this.thirdtext = "请选择三级分类";
        this.childid = "";
        this.thirdid = "";
        this.search_title = "";
        this.categoryOneCurrent = 1;
        this.categoryOneTotal = 2;
        this.categoryTwoCurrent2 = 1;
        this.categoryTwoTotal2 = 2;
        this.getCategoryOne(1);
        this.getCategorySun(1, choose[0].level, choose[0].id);
        this.currentChange(1);
      }
      // console.log(`selected ${value}`,choose[0]);
    },
    handleSelect2(value) {
      let choose = this.categoryTwo.filter((item) => {
        return item.id == value;
      });
      if (choose.length > 0) {
        this.childid = choose[0].id;
        this.categoryThree = [];
        this.thirdtext = "请选择三级分类";
        this.thirdid = "";
        this.categoryTwoCurrent2 = 1;
        this.categoryTwoTotal2 = 2;
        this.categoryThreeCurrent3 = 1;
        this.categoryThreeTotal3 = 2;
        this.getCategorySun(1, choose[0].level, choose[0].id);
        this.currentChange(1);
      }
      // console.log(`selected ${value}`,choose[0]);
    },
    handleSelect3(value) {
      let choose = this.categoryThree.filter((item) => {
        return item.id == value;
      });
      if (choose.length > 0) {
        this.thirdid = choose[0].id;
        this.categoryThreeCurrent3 = 1;
        this.categoryThreeTotal3 = 2;
        this.currentChange(1);
      }
      // console.log(`selected ${value}`,choose[0]);
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    popupScroll(e) {
      const { target } = e;
      // target.scrollTop + target.offsetHeight === target.scrollHeight  判断是否滑动到底部
      if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
        // 在这里调用接口
        this.categoryOneCurrent += 1;
        this.getCategoryOne(this.categoryOneCurrent);
      }
    },
    popupScroll2(e) {
      const { target } = e;
      if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
        // 在这里调用接口
        this.categoryTwoCurrent2 += 1;
        this.getCategorySun(this.categoryTwoCurrent2, 1, this.childid);
      }
    },
    popupScroll3(e) {
      const { target } = e;
      if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
        // 在这里调用接口
        this.categoryThreeCurrent3 += 1;
        this.getCategorySun(this.categoryThreeCurrent3, 2, this.thirdid);
      }
    },
    getCategoryOne(page = 1) {
      if (page > this.categoryOneTotal) {
        return;
      }
      $http
        .post(
          "plugin.decorate.admin.decorate-common.get-category-one",
          { page: page, categoryName: this.search_title },
          "加载更多分类数据"
        )
        .then((response) => {
          if (response.result === 1) {
            if (page == 1) {
              let item = {
                id: "",
                level: 0,
                name: "全部分类",
                parent_id: 0,
              };
              this.categoryOne = [item, ...response.data.data];
            } else {
              this.categoryOne = this.categoryOne.concat(response.data.data);
            }

            this.categoryOneCurrent = response.data.current_page;
            this.categoryOneTotal = response.data.last_page;
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    getCategorySun(page = 1, level, category_id) {
      if (level == 1) {
        if (page > this.categoryTwoTotal2) {
          return;
        }
      } else if (level == 2) {
        if (page > this.categoryThreeTotal3) {
          return;
        }
      }

      if (!category_id) {
        return;
      }

      $http
        .post(
          "plugin.decorate.admin.decorate-common.get-son-category",
          { page: page, category_id: category_id },
          "加载更多分类数据"
        )
        .then((response) => {
          if (response.result === 1) {
            if (level == 1) {
              let item = {
                id: "",
                level: 2,
                name: "选择二级分类",
                parent_id: 0,
              };
              this.categoryTwoCurrent2 = response.data.current_page;
              this.categoryTwoTotal2 = response.data.last_page;
              if (page == 1) {
                this.categoryTwo = [item, ...response.data.data];
              } else {
                this.categoryTwo = this.categoryTwo.concat(response.data.data);
              }
            } else if (level == 2) {
              let item = {
                id: "",
                level: 3,
                name: "选择三级分类",
                parent_id: 0,
              };
              this.categoryThreeCurrent3 = response.data.current_page;
              this.categoryThreeTotal3 = response.data.last_page;
              if (page == 1) {
                this.categoryThree = [item, ...response.data.data];
              } else {
                this.categoryThree = this.categoryThree.concat(
                  response.data.data
                );
              }
            }
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },

    getProjectCategory() {
      $http
        .post(
          "plugin.decorate.admin.decorate-common.get-all-store-projects-category"
        )
        .then((response) => {
          if (response.result === 1) {
            let data = response.data || [];
            let item = {
              id: "",
              name: "全部分类",
              parent_id: 0,
            };
            this.project_cate = [item, ...data];
          } else {
            this.project_cate = [];
          }
        });
    },
    handleSelectProject() {
      this.currentChange(1);
    },
    /**
     * 分页切换
     */
    currentChange(page) {

      if(this.$refs.tree) this.selectedKey[this.prevChangePages] = this.$refs.tree.getCheckedKeys();//将当前页选中的key存起来，用于最后【确认】关闭弹窗时合并起来
      this.prevChangePages = page;//记录当前页数

      this.main_page_pagination.current = page;
      let json = {};
      if (this.goods_type === "list" || this.goods_type === "store_good") {
        this.url = "plugin.decorate.admin.decorate-common.search-goods";
        if (
          this.fun.getKey("store_id") &&
          window.location.href.indexOf("store_design") > -1
        ) {
          this.url = "plugin.store-decorate.admin.decorate-common.search-goods";
        }
        if (this.goods_type === "store_good") {
          this.url =
            "plugin.decorate.admin.decorate-common.search-store-projects-goods";
        }
        json = {
          page: page,
          parentid: this.parentid,
          childid: this.childid,
          thirdid: this.thirdid,
          goods_name: this.keywords,
          goods_type: this.search_goods_type,
          goods_status: !this.goods_status ? null : this.goods_status,
          pageSize: 20,
          is_selected: this.selectedGood,
          selected_ids: this.selectedRowKeys || [],
        };
      } else if (this.goods_type === "rush") {
        this.url = "plugin.decorate.admin.decorate-common.search-flashsale";
        json = {
          page: page,
          time_status: !this.time_status2 ? null : this.time_status2,
          goods_name: this.keywords,
          pageSize: 20,
        };
        if(this.fun.getKey('store_id') && window.location.href.indexOf('store_design') > -1) {
					// 门店装修
					this.url = 'plugin.store-decorate.admin.decorate-common.search-flashsale';
					json.store_id = this.fun.getKey('store_id');
				}
      } else if (this.goods_type === "group") {
        this.url = "plugin.decorate.admin.decorate-common.search-fight-groups";
        json = {
          page: page,
          title: this.keywords,
          time_status: !this.time_status1 ? null : this.time_status1,
        };
        if(this.fun.getKey('store_id') && window.location.href.indexOf('store_design') > -1) {
					// 门店装修
					this.url = 'plugin.store-decorate.admin.decorate-common.search-fight-group';
					json.store_id = this.fun.getKey('store_id');
				}
      } else if (this.goods_type === "ywmgroup") {
        this.url =
          "plugin.decorate.admin.decorate-common.search-ywm-fight-groups";
        json = {
          page: page,
          title: this.keywords,
          time_status: !this.time_status1 ? null : this.time_status1,
        };
      } else if (this.goods_type === "category"||this.goods_type === "categoryDraggable") {
        this.url = "plugin.decorate.admin.decorate-common.search-category";
        if (
          this.fun.getKey("store_id") &&
          window.location.href.indexOf("store_design") > -1
        ) {
          this.url =
            "plugin.store-decorate.admin.decorate-common.search-category";
        }
        json = {
          page: page,
          title: this.keywords,
        };
      } else if (this.goods_type === "tag") {
        this.url = "plugin.decorate.admin.decorate-common.search-filtering";
        json = {
          page: page,
          title: this.keywords,
        };
      } else if (this.goods_type === "supplier") {
        this.url = "plugin.decorate.admin.decorate-common.search-supplier";
        json = {
          page: page,
          username: this.keywords,
        };
      } else if (this.goods_type === "store") {
        this.url = "plugin.decorate.admin.decorate-common.search-store";
        json = {
          page: page,
          store_name: this.keywords,
        };
      } else if (this.goods_type === "hotel") {
        this.url = "plugin.decorate.admin.decorate-common.search-hotel";
        json = {
          page: page,
          hotel_name: this.keywords,
        };
      } else if (this.goods_type === "starGroup") {
        this.url = "plugin.decorate.admin.decorate-common.searchStarSpell";
        json = {
          page: page,
          title: this.keywords,
        };
      } else if (this.goods_type === "project") {
        this.url =
          "plugin.decorate.admin.decorate-common.search-store-projects";
        json = {
          page: page,
          category_id: this.current_project_cate,
          title: this.keywords,
        };
      } else if (this.goods_type === "store_category") {
        this.url = "plugin.decorate.admin.decorate-common.store-category";
        if (
          this.fun.getKey("store_id") &&
          window.location.href.indexOf("store_design") > -1
        ) {
          this.url =
            "plugin.store-decorate.admin.decorate-common.store-category";
        }
        json = {
          page: page,
          keyword: this.keywords,
        };
      }
      if (this.extinfo) {
        // 额外请求参数，通过props传入
        json = { ...json, ...this.extinfo };
      }
      $http
        .post(this.url, json, "loading")
        .then((response) => {
          if (response.result === 1) {
            if (this.goods_type === "category"||this.goods_type === "categoryDraggable") {
              this.main_page_pagination.total = response.data.total || 0;
              this.main_page_pagination.pageSize = response.data.per_page || 0;
              this.main_page_list = response.data.data;
              this.$nextTick(() => {
                this.$refs.tree.setCheckedNodes(this.selectedRows);
              });
            } else if (this.goods_type === "tag") {
              this.main_page_pagination.total = response.data.length;
              this.main_page_list = response.data;
              this.$nextTick(() => {
                this.$refs.tree.setCheckedNodes(this.selectedRows);
              });
            } else {
              this.main_page_pagination.total = response.data.total || 0;
              this.main_page_pagination.pageSize = response.data.per_page || 0;
              this.main_page_list = response.data.data || [];
              this.category_to_option_open =
                response.data.category_to_option_open;
              // old_main_page_list存储原始数据
              this.old_main_page_list = JSON.parse(
                JSON.stringify(this.main_page_list)
              );
            }
            if (
              (this.goods_type === "list" ||
                this.goods_type === "store_good") &&
              this.category_to_option_open == 1
            ) {
              // 回显商品分类数据
              for (let i = 0; i < this.main_page_list.length; i++) {
                if (
                  this.selectedRowKeys.indexOf(this.main_page_list[i].id) > -1
                ) {
                  // 获取选中商品的category_id
                  let obj =
                    this.selectedRows[
                      this.selectedRowKeys.indexOf(this.main_page_list[i].id)
                    ];
                  this.main_page_list[i].category_id = obj.category_id;
                  if (obj.category_id) {
                    let record = obj.has_many_goods_category.filter((item) => {
                      return item.category_id == obj.category_id;
                    });
                    if (record[0] && record[0].goods_option) {
                      if (record[0].goods_option.thumb)
                        this.main_page_list[i].thumb =
                          record[0].goods_option.thumb;
                      this.main_page_list[i].price =
                        record[0].goods_option.product_price;
                      this.main_page_list[i].market_price =
                        record[0].goods_option.market_price;
                    }
                  }
                }
              }
            }
          } else {
            this.main_page_list = [];
            if (response.data.status === -1) {
              this.currentChange(1);
            }
            // this.$message.error(response.msg);
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleCheck(data, checked) {
      let arr = [];
      checked.checkedNodes.map((item) => {
        // 统计父级
        arr.push(item.parent_id);
      });

      this.treeSelects[this.main_page_pagination.current] =
        checked.checkedNodes;
      this.selectedRows = this.selectedRows.filter(function (item) {
        // 过滤掉多余数据和父级
        return (
          item.id != data.id &&
          item.id != data.parent_id &&
          item.parent_id != data.id &&
          !arr.includes(item.id)
        );
      });
      this.treeSelects.map((item) => {
        // 重新添加
        this.selectedRows.push(...item);
      });
      this.selectedRows = this.unique(this.selectedRows); // 去重

      if(this.goods_type === "categoryDraggable"){
        // 处理 分类页装修的编辑（即：重新进入弹窗选择） ========================================
        let parent_id = 0;
        let tree = this.$refs.tree;
        if(data.parent_id == 0){
          // 说明本次点击的是 一级
          parent_id = data.id;
        } else {
          if (tree.getNode(data.id).data.parent_id != 0) {
            // 点的是三级
            let _parent = tree.getNode(data.id).parent.data;//获取到二级的
            if (_parent.parent_id != 0) {
              parent_id = _parent.parent_id
            } else {
              parent_id = _parent.id
            }
          }else{
            // 二级
            parent_id = tree.getNode(data.id).data.id;
          }
        }
        console.log("==========该分类的父分类id为========",parent_id)
        this.oldAllSelectedList.every((item,index)=>{
          if(item.id == parent_id) {
            this.oldAllSelectedList.splice(index,1);//删除有操作过的记录，后面确认关闭弹窗时，再通过tree获取到节点补上的
            return false;
          }
          return true;
        })
      }
    },

    onSelectChange(record, selected, selectedRows) {
      if (selected) {
        this.selectedRowKeys.push(record.id);
        this.selectedRows.push(record);
      } else {
        this.selectedRowKeys = this.selectedRowKeys.filter(function (item) {
          return item != record.id;
        });
        this.selectedRows = this.selectedRows.filter(function (item) {
          return item.id != record.id;
        });
      }

      // console.log('selectedRowKeys changed: ', this.selectedRowKeys, this.selectedRows);
    },

    onSelectAll(selected, selectedRows, changeRows) {
      if (selected) {
        this.selectedRows.push(...changeRows);
        changeRows.map((item) => {
          this.selectedRowKeys.push(item.id);
        });
      } else {
        changeRows.map((record) => {
          this.selectedRowKeys = this.selectedRowKeys.filter(function (item) {
            return item != record.id;
          });
          this.selectedRows = this.selectedRows.filter(function (item) {
            return item.id != record.id;
          });
        });
      }
      // console.log(selected, selectedRows, changeRows);
    },

    unique(arr) {
      // return Array.from(new Set(arr))
      let array = [];
      let selectedRows = [];
      for (let i = 0; i < arr.length; i++) {
        if (!array.includes(arr[i].id)) {
          //includes 检测数组是否有某个值
          array.push(arr[i].id);
          selectedRows.push(arr[i]);
        }
      }
      return selectedRows;
    },

    /**
     *  打开弹窗
     * @param {Array} list 当前选中的id
     */
    show(list) {
      this.keywords = "";
      this.time_status1 = "";
      this.time_status2 = "";
      this.search_goods_type = "";
      this.goods_status = "";
      this.selectedRowKeys = [];
      this.current_project_cate = "";
      if (
        this.is_from !== "store" &&
        this.config.choose === "good" &&
        (this.goods_type === "list" || this.goods_type === "store_good")
      ) {
        this.init();
        this.getCategoryOne();
      }
      if (this.goods_type === "tag" || this.goods_type === "category"|| this.goods_type === "categoryDraggable") {
        this.selectedRows = JSON.parse(JSON.stringify(list));
      } else {
        list.forEach((item) => {
          this.selectedRowKeys.push(item.id);
        });
        this.selectedRows = JSON.parse(JSON.stringify(list));
      }
      if (this.goods_type === "project") {
        this.getProjectCategory();
      }
      this.currentChange(1);
      this.visible = true;
    },
    init() {
      this.parentid = "";
      this.childid = "";
      this.thirdid = "";
      this.parenttext = "";
      this.search_title = "";
      this.childtext = "请选择二级分类";
      this.thirdtext = "请选择三级分类";
      this.categoryOne = [];
      this.categoryOneCurrent = 1;
      this.categoryOneTotal = 2; //为了第一次加载需要先设置为2
      this.categoryTwo = [];
      this.categoryTwoCurrent2 = 1;
      this.categoryTwoTotal2 = 2;
      this.categoryThree = [];
      this.categoryThreeCurrent3 = 1;
      this.categoryThreeTotal3 = 2;
    },

    /**
     * 确认按钮
     */
    handle_confirm() {
      if (this.goods_type === "tag" || this.goods_type === "category"||this.goods_type === "categoryDraggable") {
        this.treeSelects.map((item) => {
          this.selectedRows.push(...item);
        });
        this.selectedRows = this.unique(this.selectedRows); // 去重
        console.log(this.selectedRows)
        if(this.goods_type === "categoryDraggable"){
          let parentAll = [...this.oldAllSelectedList,...this.getParentNode(this.selectedRows)];
          parentAll = this.unique(parentAll);//去重
          this.selectedKey[this.main_page_pagination.current] = this.$refs.tree.getCheckedKeys();
          let _AllKeys = [];
          for (let key in this.selectedKey) {
            _AllKeys.push(...this.selectedKey[key]);
          }
          _AllKeys = [..._AllKeys,...this.oldAllcheckedKeys];
          _AllKeys = [...new Set(_AllKeys)];//去重
          this.$emit("onComfirm", this.selectedRows,{parentAll: parentAll,checkedKeys: _AllKeys});
        } else {
          this.$emit("onComfirm", this.selectedRows);
        }
      }
      // else if(this.goods_type === 'starGroup'){
      // 	this.selectedRows.forEach((item)=>{
      // 		item.tab_name="自定义名称"
      // 	})
      // 	this.selectedRows= this.unique(this.selectedRows);
      // 	this.$emit('onComfirm', this.selectedRows);
      // }
      else {
        // if(this.selectedRows.length > 100) {
        //  this.$message.error('最多只能添加100个');
        //  return
        // }
        this.$emit("onComfirm", this.selectedRows);
      }
      this.visible = false;
    },

    getParentNode(arr) {
      let tree = this.$refs.tree;
      let commit = []; //记录所有父子id，用于最后过滤出只选择的父子分类，不在这个里面就是不是选中三级或者二级
      let AllParent = []; //把一级的分类的所有都记录下来，最后用commit过滤
      let _parent = null;
      // console.log("========arr",arr)
      arr.map((item) => {
        console.log(item.name,tree.getNode(item.id));
        if(tree.getNode(item.id)){
          commit.push(item.id);
          if (tree.getNode(item.id).data.parent_id != 0) {
            _parent = tree.getNode(item.id).parent.data;
            commit.push(_parent.id);
            if (_parent.parent_id != 0) {
              commit.push(_parent.parent_id);
              AllParent.push(tree.getNode(_parent.parent_id).data);
            } else {
              AllParent.push(tree.getNode(item.id).parent.data);
            }
          } else {
            AllParent.push(tree.getNode(item.id).data);
          }
        }
      });
      AllParent = this.uniqueFunc(AllParent,'id');

      // 过滤掉没有选中的子分类（二级三级）
      let item = '';
      let itemTwo = '';
      let itemThree = '';
      for(let i=AllParent.length-1;i>=0;i--){
        // console.log(AllParent[i].name);
        item = AllParent[i]
        if (item.children && item.children.length > 0) {
          // 有children说明是上级分类，需要保留
          for(let i2=item.children.length-1;i2>=0;i2--){
            itemTwo = item.children[i2];
            // 排查是否包含在commit里，没有则不是选中的分类，删除掉
            // console.log('..........................',itemTwo.name)
            if (commit.indexOf(itemTwo.id) < 0) {
              AllParent[i].children.splice(i2, 1);
            } else if (itemTwo.children && itemTwo.children.length > 0) {
              for(let i3=itemTwo.children.length-1;i3>=0;i3--){
                itemThree = item.children[i2].children[i3];
                // 排查是否包含在commit里，没有则不是选中的分类，删除掉
                if (commit.indexOf(itemThree.id) < 0) {
                  AllParent[i].children[i2].children.splice(
                    i3,
                    1
                  );
                }
              }
            }
          }
        } else {
          // 一级分类，无需处理，直接保留
        }
      }
      
      // 过滤掉没有选中的子分类（二级三级） end====================
      return AllParent
    },
    uniqueFunc(arr, uniId) {
      const res = new Map();//定义常量 res,值为一个Map对象实例
      return arr.filter(
        //返回arr数组过滤后的结果，结果为一个数组
        //过滤条件是，如果res中没有某个键，就设置这个键的值为1
        (item) => !res.has(item[uniId]) && res.set(item[uniId], 1)
      );
    },
    /**
     * 取消按钮
     */
    handle_cancel() {
      this.visible = false;
    },
  },
};
</script>


<style lang="less" scoped>
.btn-remove {
  margin-left: 10px;
  margin-bottom: 10px;
}

.goods_tab {
  // 序号
  .number {
    width: 80px;
    margin-left: 10px;
  }

  .goods_img {
    height: 60px;
    line-height: 60px;

    & > img {
      width: auto;
      height: auto;
      max-height: 100%;
      max-width: 100%;
    }
  }

  .ant-checkbox-wrapper,
  .ant-checkbox-wrapper + .ant-checkbox-wrapper {
    margin-right: 0px !important;
  }
}

.replace-goods-wrap {
  padding-right: 22px;

  .title {
    margin-bottom: 6px;
  }

  .img {
    margin-top: 12px;
    margin-bottom: 6px;
  }

  .goods_image {
    height: 440px;

    & > img {
      width: auto;
      height: auto;
      max-height: 100%;
      max-width: 100%;
    }
  }
}
</style>

<style lang="less">
// SKU 管理弹窗
.goods-sku-manager {
  // 选项按钮
  .ant-btn {
    padding: 0 8px;
  }
  // 表头
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    padding: 16px 0px !important;
  }

  .el-tree-node__label {
    font-size: 16px;
  }
}

.store_box {
  display: flex;
  img {
    width: 100%;
  }
}
</style>
